package ga.mutation;

import ga.GARun;
import ga.individuals.Individual;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.ArrayUtils;

import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.MWNumericArray;

public class ClassicMutation implements MutationMethod {
	
	@Override
	public Collection<Individual> method(Collection<Individual> individuals) {
		Collection<Individual> newIndividuals = new LinkedList<Individual>();
		Double pMut = GARun.mutationProb;
		Random randomForMut = new Random(System.currentTimeMillis());
		Random randomForVar = new Random(System.currentTimeMillis());
		for (Individual individual: individuals) {
			MWNumericArray individualValue = individual.getIndividualValue();
			double[] data = (double[])individualValue.getDoubleData();
			
			List<Double> dataList = Arrays.asList(ArrayUtils.toObject(data));

			double min = Collections.min(dataList);
			double max = Collections.max(dataList);			
			
			// TODO esto que hice es fruta mal... ver la posta dps
			for (int i = 0 ; i < data.length ; i++) {
				if (randomForMut.nextDouble() < pMut) {
					double newValue = randomForVar.nextDouble() * (max - min) + min;
					data[i] += newValue;
				}
			}
			try {
				newIndividuals.add(new Individual(new MWNumericArray(data)));
			} catch (MWException e) {
				e.printStackTrace();
			}
		}
		return newIndividuals;
	}
}
